package goes

import (
	"crypto/tls"
	"crypto/x509"
	"net/http"
	"os"

	"gitee.com/fish-afraid-of-water/goes/logger"
	"github.com/elastic/go-elasticsearch/v7"
	"github.com/pkg/errors"
	_ "gorm.io/gorm"
)

type ES struct {
	client *elasticsearch.Client
	logger logger.Interface
}

func NewES(cfg Config) (*ES, error) {
	c, err := newClient(cfg.ClientConfig)
	if err != nil {
		return nil, errors.Wrap(err, "创建 es 客户端失败")
	}

	if cfg.Logger == nil {
		cfg.Logger = &logger.ConsoleLogger{}
	}

	es := &ES{
		client: c,
		logger: cfg.Logger,
	}

	return es, nil
}

func newClient(cfg ClientConfig) (*elasticsearch.Client, error) {

	caCertPool := x509.NewCertPool()
	if !cfg.SkipCert {
		caCert, err := os.ReadFile(cfg.CertFile)
		if err != nil {
			return nil, errors.Wrap(err, "加载证书失败")
		}
		caCertPool.AppendCertsFromPEM(caCert)
	}

	c, err := elasticsearch.NewClient(elasticsearch.Config{
		Addresses: cfg.URLs,
		Username:  cfg.Username,
		Password:  cfg.Password,
		Transport: &http.Transport{
			TLSClientConfig: &tls.Config{
				InsecureSkipVerify: cfg.SkipCert,
				RootCAs:            caCertPool,
			},
		},
	})
	if err != nil {
		return nil, err
	}
	return c, nil
}
